#pragma once
#include <windows.h>
#include <iostream>
#include <windows.h>
#include <iostream>
#include <TlHelp32.h>
#include <Psapi.h>
#include <windows.h>
#include <iostream>
#include <iostream>
#include <string>
#include <windows.h>
#include <locale>
#include <codecvt>
#include <iomanip>
#include <windows.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <ranges>
#include <windows.h>
#include <psapi.h>
#include <iostream>
#include <vector>
#include <map>
#include <list>
struct MemoryInfo {
	UINT64 address;
	MEMORY_BASIC_INFORMATION mbi;
};
class Scanner {
	DWORD process_id = 0;
	HANDLE process_handle = 0;
public:
	std::list<std::shared_ptr<MemoryInfo>> memories;
	Scanner(DWORD process_id) {
		this->process_handle = 0;
		this->process_id = process_id;
	}
	~Scanner() {
		close();
	}
	bool open() {
		close();
		process_handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id);
		return process_handle != 0;
	}
	void close() {
		if (process_handle) {
			CloseHandle(process_handle);
			process_handle = 0;
		}
	}
	std::vector<UINT64> search(const void* value, SIZE_T size) const {
		std::vector<UINT64> results;
		if (!process_handle) return results;

		UINT64 address = 0;
		MEMORY_BASIC_INFORMATION mbi;

		// 遍历所有内存区域
		while (1) {
			auto result = VirtualQueryEx(process_handle, (LPCVOID)address, &mbi, sizeof(mbi));
			if (!result) break;

			// 只处理可读且已提交的内存
			if (mbi.State == MEM_COMMIT &&
				(mbi.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE)) &&
				!(mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS))) {

				// 分配缓冲区并读取内存
				std::vector<BYTE> buffer(mbi.RegionSize);
				SIZE_T bytesRead = 0;

				if (ReadProcessMemory(process_handle, mbi.BaseAddress, buffer.data(), mbi.RegionSize, &bytesRead)) {
					// 在缓冲区中搜索值
					for (SIZE_T i = 0; i <= bytesRead - size; i++) {
						if (memcmp(buffer.data() + i, value, size) == 0) {
							results.push_back((UINT64)mbi.BaseAddress + i);
						}
					}
				}
			}

			//std::shared_ptr<MemoryInfo> info = std::make_shared<MemoryInfo>();
			//info->address = 0;
			//memcpy(&info->mbi, &mbi, sizeof(mbi));

			//memories.push_back(info);

			// 移动到下一个内存区域
			address = (UINT64)mbi.BaseAddress + mbi.RegionSize;
		}
		return results;
	}
};
